<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form ref="form" :model="form" label-position="left" label-width="80px">
          <el-row :gutter="20">
              <el-col :span="5">
                <el-form-item label="建筑群">
                  <FilterSelect2
                      v-model="form.buildingId"
                      :optionlist="qiyelist"
                      @updateModelValue="changeqiye"
                      :valuekey="{ name: 'name', value: 'id' }"
                    ></FilterSelect2>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="用户">
                  <FilterSelect2
                      v-model="form.customerId"
                      :optionlist="yonghulist"
                      :valuekey="{ name: 'customerName', value: 'id' }"
                    ></FilterSelect2>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="用能类型">
                  <el-select size="small" v-model="form.energyType" style="width: 100%;">
                    <el-option v-for="(item,index) in yomgnenglist" :key="index" :label="item.text" :value="item.value" class="option"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5" >
                <el-form-item label="月份">
                  <el-date-picker
                  style="width: 100%;;"
                    v-model="value1"
                    type="monthrange"
                    range-separator="-"
                    value-format="yyyy-MM"
                    size="small"
                    start-placeholder="开始月份"
                    end-placeholder="结束月份">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="4" style="text-align: right;">
                <el-form-item label="">
                  <el-button @click="chongzhi"  size="small">重 置</el-button>
                  <el-button @click="getdatalist()" type="primary" size="small">查 询</el-button>
                </el-form-item>
              </el-col>
          </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="title" style="display:flex;justify-content:space-between;">
        <div>用电月报</div>
         <div> <TopTile  @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile></div>
      </div>
      <div class="tablebox">
        <TableColumn
        ref="tabledata"
        :tableData="tableData" 
        :tableConfig="tableConfig" 
        :issize="issize">
        <el-table-column
          prop="apportionStatus"
          label="分摊情况">
          <template #default="{row}">
            <span :style="{color:row.apportionStatus=='无分摊'||row.apportionStatus=='已结算'?'':'red'}">{{ row.apportionStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalCoverFee"
          width="110"
          label="总服务费(元)"
          align="right">
        </el-table-column>
        <el-table-column
          prop="totalAmount"
          width="100"
          label="总电费(元)"
          align="right">
        </el-table-column>
        <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="100">
            <template #default="{row}">
              <el-tooltip class="item" effect="dark" content="浏览" placement="top">
                <i @click="chakan(row)" class="el-icon-view" style="color: #1a90fe;cursor: pointer;"></i>
              </el-tooltip>
            </template>
        </el-table-column>
       </TableColumn>
      </div>
       <!-- 底部分页 -->
      <div class="fenye">
        <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pageobj.pageNo"
                :page-size="20"
                @current-change="getdatalist"
                :total="+totalCount">
          </el-pagination>
        </div>
      <!-- 查看详情弹窗 -->
      <div class="dialog">
        <el-dialog
          :title="title"
          :visible.sync="dialogVisible"
          width="64%">
          <div>
            <div class="pfd">
              <div></div>
               <el-button @click="exportpdf" type="primary" size="small">下载PDF</el-button>
            </div>
            <div class="diatext">
              <div class="text bgc">用户名称</div>
              <div class="text">{{ rowvalue.customerName}}</div>
              <div class="text bgc">用户编号</div>
              <div class="text">{{  rowvalue.customerCode }}</div>
            </div>
            <div>
              <el-collapse v-model="activeNames">
                  <el-collapse-item  v-for="(item,index) in forlist" :key="index" :name="item.meterId">
                    <span class="collapse-title" slot="title">{{ item.meterName }}</span>
                    <div class="title">
                      <div>抄表周期：{{ item.meterReadingCycleStartDate }} 至 {{item.meterReadingCycleEndDate  }}</div>
                      <div>抄表时间：{{ item.meterReadingStartDate }} 至 {{ item.meterReadingEndDate }}</div>
                    </div>
                    <div class="dianfeitable">
                      <TableColumn
                        ref="tabledata"
                        :tableData="item.childenlist" 
                        :tableConfig="tableConfigs" 
                        size="medium">
                      </TableColumn>
                    </div>
                  </el-collapse-item>
              </el-collapse>
            </div>
            <div class="dianfei">分摊电费</div>
              <div>
                <TableColumn
                   ref="tabledata"
                   :tableData="tableDatass" 
                   :tableConfig="tableConfigss">
                   <el-table-column
                    label="状态">
                    <template #default="{row}">
                      <div class="status" style="display: flex;align-items: center;">
                        <div class="yuan" 
                        :style="{'background-color':row.status=='创建'?'#e64545':row.status=='待结算'?'#f4ea2a':'#36b34b'}"
                        style="height: 12px;width: 12px;border-radius: 50%;margin-right: 10px;"
                        ></div>
                        <div>{{ row.status }}</div>
                      </div>
                    </template>
                  </el-table-column>
                </TableColumn>
              </div>
              <!-- <div class="total">分摊合计：0.25元</div> -->
            </div>
          <span slot="footer" class="dialog-footer">
            <el-button  size="small" @click="dialogVisible = false">关闭</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {gettablelistapi} from '@/api/prwpaid/user-manage/OpenAaccount'
import { getzidianxialaapi } from '@/api/guidelines'
import { getloginlistapi } from '@/api/prwpaid/file-management/Architectural-complex'
import TopTile from '@/components/TopTitle/index.vue'
import TableColumn from '@/components/Table/index.vue'
import { getmonthportapi,getportmingxiapi } from '@/api/prwpaid/report-forms/month-report'
import { exportexcel } from '@/utils/excel'
import  {ExportPdf} from '@/utils/exportpdf'
import {MakemeterEleclist,MakemeterWorterlist} from './MakeList'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTile,
    TableColumn
  },
  data() {
    return {
      tableConfigss: [],
      tableDatass:[],
      tableDatas: [],
      tableConfigs: [],
      dialogVisible:false,
      issize: 'medium',
      form: {buildingId:'',customerId:'',energyType:''},
      qiyelist: [],
      yonghulist: [],
      yomgnenglist:[],
      tableData:[],
      tableConfig: [
        { label: '序号', type: 'index', center: 'center', width: '70' },
        { label: '日期', prop: 'statisticsMonth' ,center:'center'},
        { label: '建筑群名称', prop: 'buildingName',width:'200' },
        { label: '用户名称', prop: 'customerName' ,width:'200'},
        { label: '起初余额', prop: 'startBalance' ,center:'right'},
        { label: '本月充值', prop: 'rechargeAmount' ,center:'right'},
        { label: '用户用电(kWh)', prop: 'usageValue' ,center:'right',width:'130'},
        { label: '用户电费(元)', prop: 'usageAmount', center: 'right' ,width:'110'},
        { label: '分摊用电(kWh)', prop: 'apportionValue' ,center:'right',width:'130'},
        { label: '分摊电费(元)', prop: 'apportionAmount' ,center:'right',width:'110'},
        // { label: '分摊情况', prop: 'apportionStatus',
        //   formatter: (row, column, cellValue, index) => {
        //     let color = 'black';
        //     if (['未结算', '部分结算', '未分摊'].includes(cellValue)) {
        //       color = 'red';
        //     }
        //     return `<span style="color: ${color};">${cellValue}</span>`
        //   }
        // },
        // { label: '总服务费(元)', prop: 'totalCoverFee', center: 'right' },
        // { label: '总电费(元)', prop: 'totalAmount',center:'right' },
      ],
      totalCount: '',
      pageobj: {
        pageNo: 1,
        pageSize:20
      },
      title:'',
      activeNames:'',
      rowvalue: {},
      forlist: [],
      value1:[]
    };
  },

  async mounted() {
      // 获取用能类型
  const yonghu = await getzidianxialaapi({ dictType: 'MBM_ENERGY_TYPE' })
    this.yomgnenglist = yonghu.data.list
  this.form.energyType=this.yomgnenglist[0].value
        // 获取建筑群
  const res = await getloginlistapi()
    this.qiyelist = res.data.list
    const localbuildingId = localStorage.getItem('buildingId')
    const isBuildIdInArray = this.qiyelist.some(item => item.id == localbuildingId);
    if(isBuildIdInArray){
      this.form.buildingId = localbuildingId ? localbuildingId : ''
      this.getyonghuxialalist(this.form.buildingId)
    }else{
      this.form.buildingId= ''
    }
    this. gettime() 
    this.getdatalist()
  },

  methods: {
    // 企业下拉
    changeqiye(val) {
      localStorage.setItem('buildingId', val)
      this.getyonghuxialalist(val)
    },
     // 获取用户
    async getyonghuxialalist(val) {
    const ress = await gettablelistapi({
        pageNo: 0, pageSize: 500,
      startDate: '', endDate: '', 
      state:'20',buildingId:val,customerType:''
    })
    this.yonghulist = ress.data.list
    },
    // 获取表格数据
    async getdatalist() {
      this.$refs.tabledata.loading=true
      const { data: { list, totalCount } } = await getmonthportapi({
        pageNo: this.pageobj.pageNo - 1,...this.form,startMonth:this.value1[0],endMonth:this.value1[1],
        pageSize: this.pageobj.pageSize,
      })
      this.tableData = list
      this.totalCount = totalCount
      this.$refs.tabledata.loading=false
    },
    // 重置
    chongzhi() {
      localStorage.removeItem('buildingId');
      this.form = { buildingId: '', customerId: '', energyType: '', month: '' }
      this.gettime() 
    this.getdatalist()
    },
    //查看详情
    async chakan(row) {
      this.title=`${row.buildingName} ${row.customerName} ${row.statisticsMonth}月电费月报`
      this.rowvalue = row
      const energyType=this.yomgnenglist.filter(ele=>ele.text==row.energyType)[0].value
      const res= await getportmingxiapi({
      customerId:row.customerId,energyType:energyType,
        month:row.statisticsMonth
      })
      this.tableDatass = res.data.entity.appointList
      if (row.energyType=='电') {
        this.forlist = MakemeterEleclist(res.data.entity.meterList, row)
        this.tableConfigs=[      { label: '用电明细', prop: 'mingxi' },
        { label: '上期示数', prop: 'shangqi' ,center:'right'},
        { label: '本期示数', prop: 'benqi', center: 'right' },
        { label: 'CT', prop: 'ct' ,center:'right'},
        { label: 'PT', prop: 'pt', center: 'right' },
        { label: '电量(kWh)', prop: 'dianliang',center:'right'},
        { label: '单价(元/kWh)', prop: 'danjia',center:'right',width:'120'  },
          { label: '电费金额(元)', prop: 'jine', center: 'right' },]
        this.tableConfigss =[      { label: '分摊表', prop: 'meterName' },
      { label: '公共表', prop: 'publicMeterName'},
        { label: '公共表用量', prop: 'publicConsumption',center:'right'  },
        { label: '分摊用量', prop: 'apportionConsumption', center: 'right' },
        { label: '单价(元)', prop: 'unitPrice',center:'right' },
        { label: '分摊费用', prop: 'apportionFee',center:'right' },
          { label: '分摊日期', prop: 'date', center: 'center' },
        ]
      } else {
        this.forlist = MakemeterWorterlist(res.data.entity.meterList)
        this.tableConfigs=[      { label: '用水明细', prop: 'mingxi' },
        { label: '上期示数', prop: 'shangqi' ,center:'right'},
        { label: '本期示数', prop: 'benqi', center: 'right' },
        { label: '水量(吨)', prop: 'dianliang',center:'right'},
        { label: '单价(元/吨)', prop: 'danjia',center:'right',width:'120'  },
          { label: '水费金额(元)', prop: 'jine', center: 'right' },]
          this.tableConfigss =[       { label: '分摊表', prop: 'meterName' },
      { label: '公共表', prop: 'publicMeterName'},
        { label: '公共表用量', prop: 'publicConsumption',center:'right'  },
        { label: '分摊用量', prop: 'apportionConsumption', center: 'right' },
        { label: '单价(元)', prop: 'unitPrice',center:'right' },
        { label: '分摊费用', prop: 'apportionFee',center:'right' },
            { label: '分摊日期', prop: 'date', center: 'center' },
          ]
      }
      this.activeNames=this.forlist[0]?.meterId
      this.dialogVisible=true
    },
    // 导出pdf
    exportpdf() {
      const energyType=this.yomgnenglist.filter(ele=>ele.text==this.rowvalue.energyType)[0].value
      ExportPdf('mbm-microservice-biz/mbm/report/energy/month/exportDetails',{
        buildingName: this.rowvalue.buildingName, customerCode: this.rowvalue.customerCode, customerId: this.rowvalue.customerId,
        customerName: this.rowvalue.customerName,energyType:energyType,month:this.rowvalue.statisticsMonth
      },`${this.rowvalue.customerName} ${this.rowvalue.statisticsMonth}月电费月报`)
    },
  // 导出
    daochu() {
      exportexcel('mbm-microservice-biz/mbm/report/energy/month/exportExcel',
      {...this.form,startMonth:this.value1[0],endMonth:this.value1[1],}, '用水用电月报')
    },
  // 刷新
    shuaxin() {
    this.$message.success('数据刷新成功')
    this.getdatalist()
  },
  // 调节表格密度
  command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 获取当前时间戳
    gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const mon = date.getMonth() + 1 // 月
      const month = mon < 10 ? '0' + mon : mon
      this.value1=[year+'-'+'01',year+'-'+month]
      // this.form.month=year+'-'+month
      // this.form.month=year+'-'+month
    },
  },
};
</script>

<style scoped>
.bigbox{
  height: 100%;
  padding: 10px;
  .option{
    padding-left: 10px;
  }
  .topbox{
    height: 80px;
    padding: 20px;
    margin-bottom: 10px;
    background-color: #fff;
  }
  .bodybox{
    height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;
    .tablebox{
      margin-top: 10px;
      height: 88%;
    }
    .fenye{
      text-align: right;
      margin-top: 10px;
    }
    .dialog{
      .button{
        width: 60px;
        height: 30px;
        border-radius: 3px;
      }
      .pfd{
        display: flex;
        justify-content: space-between;
      }
      .diatext{
      margin-bottom: 10px;
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #ccc;
      border-top: 1px solid #ccc;
      border-right: 1px solid #ccc;
      .text{
        width: 25%;
        text-align: center;
        padding: 10px 0;
        border-left: 1px solid #ccc;
      }
      .bgc{
        background-color: #f1f1f1;
      }
    }
    .title{
      font-size: 14px;
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      color:#000;
    }
    .dianfei{
      font-size: 16px;
      margin: 10px 0;
    }
    .total{
      font-size: 16px;
      height: 50px;
      line-height: 50px;
      padding-left: 20px;
      background-color: #fafafa;
      border: 1px solid #EBEEF5;
      border-top: none;
    }
    }
  }
}
::v-deep .el-range__icon{
  margin-left:0px !important;
}
::v-deep .el-dialog__footer{
  text-align: center;
}
::v-deep .el-collapse-item__header {
  border: 1px solid #EBEEF5;
  padding: 0 20px;
  background-color: #fafafa;
 }
::v-deep .el-collapse-item__wrap{
  border: 1px solid #EBEEF5;
  padding: 20px 20px 0 20px;
}
::v-deep .el-collapse{
  border: 1px solid #EBEEF5;
}

::v-deep .collapse-title {
         flex: 1 0 90%;
         order: 1;
     }
     
::v-deep .el-collapse-item__header {
         flex: 1 0 auto;
         order: -1;
  }

</style>